document.getElementsByTagName('html')[0].className += ' ff-hasjs';

var ffBaseURL = (typeof ffBaseURL == 'undefined') ? '' : ffBaseURL;
var ffMobileWidth = 400;

function ffRewriteAnchorLinks() {
    if (document.getElementsByTagName("base").length > 0) {
        var base = document.getElementsByTagName("base")[0].href;
        var url = window.location.href;
        if (url.indexOf("#") > 0) url = url.substr(0, url.indexOf("#"));
        var links = document.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            try {
                var href = links[i].href;
                if (href) {
                    var poundPos = href.indexOf("index.html#");
                    if (href.length > base.length && href.substring(0, base.length + 1) == (base + "#")) {
                        links[i].href = url + href.substr(poundPos + 1);
                    }
                } 
            }
            catch (e) { }
        }
    }
}

if (!(typeof $ == 'undefined')) {
    $(function() {
        // rewrite anchor links if base present
        ffEventHandler.registerEvent("dominsert", function() {
            ffRewriteAnchorLinks();
        }, true);
    });
}

// page build tools - only run on page, with jquery
if (!(typeof $ == 'undefined') && !(typeof ffPageID == 'undefined')) {
    $(function() {

        // setup component edit
        $('div.componentedit').each(function() {
            setupComponentEdit(this);
        });
        // set up nav edit
        $('li.navitem.editable').hover(function() {
            $('>span.pageedit', this).css('display', 'inline');
        }, function() {
            $('>span.pageedit', this).css('display', '');
        });
        // set styles on modify tools
        $('span.pageedit a').css({ margin: 0, border: 0, padding: 0, display: 'inline' });
        // set up general reveals
        $('.parent-reveal').each(function() {
            var me = $(this);
            me.parent().hover(function() {
                if (!isMobile())
                    me.css('visibility', 'visible');
            }, function() {
                me.css('visibility', 'hidden');
            });
        });
        // set up site logo edit
        $('#ffSiteLogo').hover(function() {
            $('>span.ff-sitelogo-edit', this).css('display', 'inline');
        }, function() {
            $('>span.ff-sitelogo-edit', this).css('display', '');
        });

        // wire up search
        var searchform = $('form[action="search.aspx"]');
        if (searchform.length > 0) {
            var site_id = $('input[name="site_id"]', searchform);
            if (site_id.length > 0)
                site_id = site_id[0].value;
            else
                site_id = -1;
            var sitesection = $('input[name="sitesection"]', searchform);
            if (sitesection.length > 0)
                sitesection = sitesection[0].value;
            else
                sitesection = "";

            var query = $('input[name="query"]', searchform);
            var offsetleft = Math.round((query.outerWidth() - query.width()) / 2);
            var offsettop = 0;
            var border = (getStyle(query[0], 'borderBottomColor'));
            var bg = (getStyle(query[0], 'backgroundColor'));
            function showSearching() {
                var html = '<div class="minor-help-text">Searching...</div>';
                if ($('div#ffQuickSearch').length == 0) {
                    if (html == '') return;
                    node = $('<div id="ffQuickSearch">' + html + '</div>');
                    node.css({ 'position': 'absolute', 'top': (getTop(query[0]) + query.outerHeight() - offsettop) + 'px', 'left': (getLeft(query[0]) + offsetleft) + 'px' });
                    if (border)
                        node.css({ 'border-bottom': '1px solid ' + border, 'border-left': '1px solid ' + border, 'border-right': '1px solid ' + border, 'border-top': '0px solid ' + border });
                    if (bg && (bg.toUpperCase() != 'TRANSPARENT') && (bg.toUpperCase() != 'RGBA(0, 0, 0, 0)')) {
                        node.css({ 'background-color': bg });
                    }
                    node.css('width', query.width());
                    $('body').append(node);
                    $('body').click(function() {
                        node.hide();
                    });
                } else {
                    $('div#ffQuickSearch').html(html);
                    $('div#ffQuickSearch').show();
                }
            }
            var lastSearchQuery = '';
            function hideSearching() {
                $('div#ffQuickSearch').hide();
                lastSearchQuery = '';
            }
            function showResults(xml) {
                var html = '';
                var results = $('results > page', xml);
                for (var i = 0; i < results.length; i++) {
                    html += '<a href=\"' + results[i].getAttribute('href') + '\">' + results[i].getAttribute('title') + '</a>';
                }
                html += '';
                html += '<div class="minor-help-text">For more results, click Search.</span>';
                if (results.length == 0) html = '';
                var node = $(html);
                var posdata = query.position();

                $('div#ffQuickSearch').html(html);
                if (html == '') $('div#ffQuickSearch').hide();
                else $('div#ffQuickSearch').show();
            }
            liveChange(query[0], function() {
                if (query[0].value.length > 2 && query[0].value != lastSearchQuery) {
                    $.ajax({
                        url: "quicksearch.aspx?site_id=" + site_id + "&sitesection=" + sitesection + "&query=" + escape(query[0].value),
                        dataType: 'xml',
                        type: "GET",
                        data: {},
                        cache: false,
                        success: function(data, text) {
                            showResults(data);
                        },
                        error: function() { }
                    });
                    lastSearchQuery = query[0].value;
                }
            }, 500, function() {
                if (query[0].value.length > 2) {
                    if (query[0].value != lastSearchQuery)
                        showSearching();
                } else {
                    hideSearching();
                }
            });
            try {
                query.attr('autocomplete', 'off');
            } catch (e) { }
        }
        // set up dashboard if there
        $('div.dashboard-feed li').hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });
        $('div.dashboard-subscriptions li, .dashboard-notice-message').hover(function() {
            $('button', this).show();
        }, function() {
            $('button', this).hide();
        });
        $('.dashboard-notice-hide').bind('click', function() {
            var id = $(this).attr('data-ff-dashboard-noticeid')
            $.ajax({
                url: ffBaseURL + 'hidenotice.aspx',
                type: 'POST',
                data: { 'notice_id': id }
            });
            $(this).closest('.dashboard-type-Notice').hide(500);
        });
        $('div.dashboard-subscriptions li button').click(function() {
            var t = this;
            DashboardUnsubscribe(this.parentNode.id.substring(14), function() {
                $('li.' + t.parentNode.id).hide(500);
                $(t.parentNode).hide(500);
            });
        });
        $('div.dashboard-subscriptions li').hover(function() {
            $('li.' + this.id).addClass('hover');
        }, function() {
            $('li.' + this.id).removeClass('hover');
        });
        // wireup special edit in MS Office tools if supported
        try {
            var openDoc = new ActiveXObject("SharePoint.OpenDocuments.3");
            if (openDoc == null) openDoc = new ActiveXObject("SharePoint.OpenDocuments.2");
            if (openDoc) {
                $('a').live('click', function() {
                    try {
                        if (!this.href) return;
                        var href = $(this).attr('href');
                        if (href.indexOf('resource.aspx?') != -1) {
                            if (href.indexOf('officeint=on') == -1) {
                                $(this).attr('href', href + "&officeint=on");
                            }
                        }
                    } catch (e) { }
                });
            }
        } catch (e) { }

        // wireup autosize boxes
        var autosize_handler = function(obj) {
            var m = 0;
            var t = obj;
            $($(t).val().split("\n")).each(function(i, s) {
                m += (s.length / (t.offsetWidth / 10)) + 1;
            });

            if (isNaN(m)) m = 1;

            var height = Math.floor(m + 2);
            if (height > 20) {
                t.style.overflowY = 'auto';
                height = 20;
            } else {
                t.style.overflowY = 'hidden';
            }

            t.style.height = height + 'em';
        }
        $('textarea.ff-autosize').live('click', function(e) {
            autosize_handler(e.target);
        }).live('keyup', function(e) {
            autosize_handler(e.target);
        }).live('change', function(e) {
            autosize_handler(e.target);
        }).each(function() {
            autosize_handler(this);
        });

        // comment highlighting
        $('.commentreplycount').hover(function() {
            var wrapper = $(this).closest('.commentwrapper');
            var comment = $(this).closest('.comment');
            if ($('>.commentreplies', wrapper).length > 0) {
                var tohighlight = $('>.commentreplies>.commentwrapper>.comment', wrapper);
                $('.comment:visible').removeClass('commenthighlightedreply').not(comment).not(tohighlight).stop().fadeTo(200, 0.3);
                tohiglight.css('opacity', '');
            }
        }, function() {
            var wrapper = $(this).closest('.commentwrapper');
            var comment = $(this).closest('.comment');
            $('.comment:visible').not(comment).stop().css('opacity', '');
        });

        // calendar autosizing
        var autoSize = function() {
            var calMinWidth = 350;
            // do calendars as well
            $('.ff-calendar-tabular').each(function() {
                var $t = $(this);
                if (!$t.is(':visible')) {
                    return;
                }
                if ($t.width() < calMinWidth) {
                    $t.addClass('ff-calendar-minitabular');
                    $t.removeClass('ff-calendar-tabular');
                    $t.data('ff-prev-class', 'ff-calendar-tabular');
                }
            });
            $('.ff-calendar-minitabular').each(function() {
                var $t = $(this);
                if (!$t.is(':visible')) {
                    return;
                }
                if (!$t.data('ff-prev-class'))
                    return;
                else if ($t.width() > calMinWidth) {
                    $t.addClass($t.data('ff-prev-class'));
                    $t.removeClass('ff-calendar-minitabular');
                    $t.data('ff-prev-class', null);
                }
            });
        };

        addResizeEvent(autoSize);
        ffEventHandler.registerEvent('componentmoved', autoSize, true);

        // calendar paging
        var checkPaging = function() {
            $('.ff-calendar-tabular, .ff-calendar-minitabular').each(function() {
                if ($('.ff-calendar-group-paging', this).size > 0) return;
                if ($('.ff-calendar-group-name', this).size == 0) return;
                var groups = $('.ff-calendar-group-name', this);
                groups.each(function() {
                    var buttons = '';
                    var pgroup = $(this).parents('.ff-calendar-group');
                    if (pgroup.prev('.ff-calendar-group').length > 0)
                        buttons += '<button class="ff-calendar-group-paging-back" type="button">&lt;</button>';
                    if (pgroup.next('.ff-calendar-group').length > 0)
                        buttons += ' <button class="ff-calendar-group-paging-forward" type="button">&gt;</button>';

                    $(this).prepend("<div class='ff-calendar-group-paging'>" + buttons + "</div>");
                });
            });
        };
        checkPaging();
        $('.ff-calendar-group-paging-back').live('click', function() {
            var group = $(this).parents('.ff-calendar-group');
            group.hide();
            group.prev('.ff-calendar-group').show();
        });
        $('.ff-calendar-group-paging-forward').live('click', function() {
            var group = $(this).parents('.ff-calendar-group');
            group.hide();
            group.next('.ff-calendar-group').show();
        });
    })
};
function ffStoreData(t, n, d) {
	$(t + ':last').data(n, d);
}
function ffGetData(id, n) {
	return $('#' + id).data(n);
}
function setupTextValidation(el, regex) {
	if (!regex) { regex = /[0-9]/; };
	$(el).bind("keypress", function(evt) { 
		var charCode = evt.which;
		if (charCode < 13) return true;
		var keyChar = String.fromCharCode(charCode); 
		return regex.test(keyChar);
	});
}
function pulselight(el) {
    highlight(el, true);
    setTimeout(function() { highlight(el, false); }, 200);
}
function liveChange(el, fn, delay, immediatefn) {
    var timer;
	if (!delay) delay = 500;
	$(el).keyup(function() {
	    if (immediatefn) immediatefn();
	    if (timer) clearTimeout(timer);
	    var me = $(this);
	    if (!fn) fn = function() { me.trigger('change'); };
	    timer = setTimeout(fn, delay);
	});
}
function makeResourceList(id, sort_type, sort_reverse) {
    $(function() {
        var container = $('#' + id);
        $('tr.resource-list-folder', container).live('click', function(e) {
            if ($(e.target).parents('tr')[0] != $(this)[0]) return;
            var id = $(this).get(0).id.substring(20);
            var el = $('td', this)[1];
            var tb = $('table', el);
            if (tb.length > 0) {
                tb.toggle(300);
                return false;
            }
            $.ajax({
                url: "Admin/editor/serverside/resourcelist.aspx?fid=" + id + "&st=" + sort_type + "&sr=" + sort_reverse,
                dataType: 'xml',
                type: "POST",
                success: function(data, text) {
                    var items = data.getElementsByTagName('resource');
                    var folders = data.getElementsByTagName('resourcefolder');
                    var html = '<table class="resource-list" id="ffResourceListFolder' + id + '" style="display: none">';
                    for (var i = 0; i < folders.length; i++) {
                        if (folders[i].getAttribute('deleted') == 'yes') continue;
                        html += '<tr class="resource-list-folder" id="ffResourceListFolder' + folders[i].getAttribute('id') + '"><td valign="top"><img src="' + escape(folders[i].getAttribute('icon')) + '"></td><td valign="top"><a href="#">' + folders[i].getAttribute('name') + '</a></td><td valign="top"></td></tr>';
                    }
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].getAttribute('deleted') == 'yes') continue;
                        html += '<tr><td valign="top"><img src="' + escape(items[i].getAttribute('icon')) + '"></td><td valign="top"><a href="resource.aspx?id=' + items[i].getAttribute('id') + '">' + items[i].getAttribute('name') + '</a></td><td valign="top">' + items[i].getAttribute('description') + '</td></tr>';
                    }
                    html += '</table>';
                    var node = $(html);
                    $(el).append(node);
                    node.ffShow(300);

                },
                error: function() { },
                data: {}
            });
            return false;
        });
    });
}
var MESSAGE_URL = 'hidemessages.aspx';
function buildMessages(messages) {
    var html = '<div id="ffMessages" class="ff-blast-messages">';
    for (var i = 0; i < messages.length; i++) {
        html += '<div class="ff-blast-message" id="ffMessage' + messages[i].g + '">';
        html += '<div class="ff-blast-message-title">' + messages[i].t + '</div>';
        html += '<div class="ff-blast-message-body">' + messages[i].b + '</div>';
        html += '</div>';
    }
    html += '<div id="ffMessagesHide">Hide</div>';
    html += '</div>';
    $(document.body).append(html);
    var display = $('#ffMessages');
    var height = display.outerHeight();
    $('#ffMessagesHide').click(function() {
        var guids = '';
        for (var i = 0; i < messages.length; i++) {
            guids += messages[i].g + '|';
        }
        if (guids.substring(guids.length - 1) == '|') guids = guids.substring(0, guids.length - 1);
        $.ajax({
            url: ffBaseURL + MESSAGE_URL,
            type: 'POST',
            data: { 'guids': guids }
        });
        display.animate({ 'top': '-' + height + 'px' }, 'fast');
    });
    display.css('top', '-' + height + 'px');
    display.animate({ 'top': '0px' }, 1000);

}
function buildUserBar(title, menu, impersonating) {


    var output = "";
    output += impersonating ? '<div class="ff-nav-sitewide ff-nav-sitewide-impersonating">\n' : '<div class="ff-nav-sitewide">\n';
    output += ' <div class="ff-wrapper">\n';
    output += '   <div class="ff-site-name">\n';
    output += '     <p>' + title + '</p>\n';
    output += '   </div>\n';
    output += '   <ul>\n';
    for (var i in menu) {
        if (menu[i].menu)
            output += '     <li class="has-children">';
        else
            output += '     <li>';

        if (menu[i].href && menu[i].help)
            output += '<a href="' + menu[i].href + '" title="' + menu[i].help + '">';
        else if (menu[i].href)
            output += '<a href="' + menu[i].href + '">';
        else
            output += '<a href="">';
            
        output += menu[i].title;
        output += '</a>\n';

        if (menu[i].menu) {
            output += '     <ul>\n';
            for (var j in menu[i].menu) {
                if (menu[i].menu[j].help)
                    output += '         <li><a href="' + menu[i].menu[j].href + '" title="' + menu[i].menu[j].help + '">';
                else
                    output += '         <li><a href="' + menu[i].menu[j].href + '">';
                output += menu[i].menu[j].title;
                output += '</a></li>\n';
            }
            output += '     </ul>\n';
        }
        
        output += '     </li>\n';
    }
    output += '   </ul>\n';
    output += ' </div>\n';
    output += '<div style="clear: left"></div></div>\n';
    //document.write(output);
    $("body").prepend(output);
    
    $('.ff-nav-sitewide ul li').hover(function() {
        $(this).toggleClass("hover");
    });

    $('.ff-nav-sitewide ul li.has-children > a').click(function() {
        return false;
    });
}
function buildToolbox(tools, extendheight) {

	var COMPONENT_HELPER_URL = 'Admin/editor/serverside/componentproperties.aspx?id=';
	
	var componentTypes = {};
	var componentDirty = true;
	if (!extendheight) extendheight = '';
	var selectedComponent = -1;
	var selectedPage = -1;
	var pageWrite = false;
	
	var html = '<div id=\'ffToolbox\'>';
	html += '<h2>Edit Toolbox</h2>';
	var flyouts = false;
	
	for (var i = 0; i < tools.length; i++) {
		if (tools[i].items) {
			html += '<h3><img src=\'Templates/acc-expand.gif\'> ' + tools[i].l + '</h3>';
			html += '<div style=\'display: none\'>';
			for (var j = 0; j < tools[i].items.length; j++) {
			    var accesskey = '';
			    if (tools[i].items[j].ak && (tools[i].items[j].ak != '')) { accesskey = ' accesskey="' + tools[i].items[j].ak + '"'; }
				html += '<a href=\'' + tools[i].items[j].u + '\' title="' + tools[i].items[j].h + '"' + accesskey + '>' + tools[i].items[j].l + '</a>';
			}
			html += '</div>';
			flyouts = true;
		}
		else {
		    var accesskey = '';
		    if (tools[i].ak && (tools[i].ak != '')) { accesskey = ' accesskey="' + tools[i].ak + '"'; }
			if (tools[i].u.substring(0,5) == 'index.html')
			    html += '<a href=\'' + tools[i].u + '\' class=\'promote-tool\' target=\'_new\' title="' + tools[i].h + '"' + accesskey +'>' + tools[i].l + '</a>';
			else
			    html += '<a href=\'' + tools[i].u + '\' class=\'promote-tool\' title="' + tools[i].h + '"' + accesskey + '>' + tools[i].l + '</a>';
		}
    }

	html += '<h3 id=\'ffTBC\'><img src=\'Templates/acc-expand.gif\'> Edit component</h3>';
	html += '<div style=\'display: none\' id=\'ffTBCD\'><span>Click a component to select it</span><span style=\'display: none\'>';
	html += '<a href=\'#\' id=\'ffTBCM\' title=\'Change the contents of this component\'>Modify component</a>';
	html += '<span id=\'ffTBCPW\'><a href=\'#\' id=\'ffTBCD\'>Delete component</a>';
	html += '<a href=\'#\' id=\'ffTBCP\' title=\'Change who can see or edit this component\'>Modify permissions</a>';
	html += '<label for=\'ffTBCH\' title=\'Optionally enter some header text to appear above the component in the page\'>Header</label>';
	html += '<input id=\'ffTBCH\' type=\'text\' title=\'Optionally enter some header text to appear above the component in the page\'>';
	html += '<label for=\'ffTBCW\' title=\'Choose whether other components on the page should wrap around this one\'>Wrapping</label>';
	html += '<select id=\'ffTBCW\' title=\'Choose whether other components on the page should wrap around this one\'><option>No wrapping</option><option>Wrap to right</option><option>Wrap to left</option></select>';
	html += '<span id=\'ffTBCWs\'><label for=\'ffTBCWw\'>Width</label>';
	html += '<input id=\'ffTBCWw\' type=\'text\' size=\'3\' style=\'width: 50px; float: left; margin-right: 3px\'> pixels</span>';
	html += '<label for=\'ffTBCT\' title=\'Select the style of this component - this will affect how it is displayed in the page, as determined by the template\'>Style</label>';
	html += '<select id=\'ffTBCT\' title=\'Select the style of this component - this will affect how it is displayed in the page, as determined by the template\'></select>';
	html += '<span id=\'ffTBCCc\'><label for=\'ffTBCC\'>Container</label>';
	html += '<select id=\'ffTBCC\'></select></span>';
	html += '</span></span></div>';


	function selectComponent(id) {
		if (selectedComponent == id) return;
		else componentDirty = true;
		selectedComponent = id;

		if ($('h3#ffTBC + div').is(':visible') && expanded) {
		    selectComponentLive();
		}
		$('h3#ffTBC+div > span').last().hide();
		if (selectedComponent > -1) {
		    $('h3#ffTBC+div > span').first().text('Loading...').show();
		}
		else {
		    $('h3#ffTBC+div > span').first().text('Click an editable component to select it').show();
		}
         		 
	}
	function selectComponentLive() {
	    $.ajax({
	        url: ffBaseURL + COMPONENT_HELPER_URL + selectedComponent,
	        dataType: 'xml',
	        type: "GET",
	        cache: false,
	        success: function(data) { fillProperties(data); },
	        error: function() {  }
	    });
        componentDirty = false;
	}
	
	
	
	function updateWrapDisplay() {
	    document.getElementById('ffTBCWs').style.display = (document.getElementById('ffTBCW').selectedIndex > 0) ? '' : 'none';
	    if ((document.getElementById('ffTBCWs').style.display == '') && (document.getElementById('ffTBCWw').value == '')) {
		var width = 200;
	        document.getElementById('ffTBCWw').value = width;
	    }
	}
	
	function fillProperties(xml) {

		document.getElementById('ffTBCH').value = $('header', xml).text();
		selectedPage = $('component', xml).attr('page_id');
		pageWrite = ($('component', xml).attr('page_write') == 'yes');

		if (pageWrite) {

		    $('#ffTBCPW').show();
		
			document.getElementById('ffTBCW').selectedIndex = parseInt($('float', xml).text());
			document.getElementById('ffTBCWw').value = ($('width', xml).text() == '0') ? '' : parseInt($('width', xml).text());
			updateWrapDisplay();
			
			var types = document.getElementById('ffTBCT');
			types.options.length = 0;
			var i = 0;
			var sel = 0;
			componentTypes = {};
			$('type', xml).each(function() {
				types.options[types.options.length] = new Option(this.getAttribute('label'), this.getAttribute('id'));
				componentTypes['ff' + this.getAttribute('id')] = this.getAttribute('cssclass');
				if (this.getAttribute('selected') == 'yes') { sel = i; prevtype = this.getAttribute('id'); }
				i++;
			});
			types.selectedIndex = sel;
			
			var containers = document.getElementById('ffTBCC');
			containers.options.length = 0;
			i = 0;
			sel = 0;
			$('container', xml).each(function() {
				containers.options[containers.options.length] = new Option(this.getAttribute('label'), this.getAttribute('id'));
				if (this.getAttribute('selected') == 'yes') { sel = i; prevtype = this.getAttribute('id'); }
				i++;
			});
			containers.selectedIndex = sel;
			
		} else {
			$('span#ffTBCPW').hide();
			// only show the modify button if you can't write the page
		}
		
		$('h3#ffTBC+div').children('span').last().show();
		$('h3#ffTBC+div').children('span').first().hide();
	}
	
	function setContainer(cont) {
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		var existing = c.parent()[0].id.substring(11);
		if (existing != cont) {
			$('#ffContainer' + cont).append(c);
			c[0].scrollIntoView();
			updateTargetContainer(selectedPage, document.getElementById('ffContainer' + cont), true);
			ffEventHandler.pushEvent('dominsert');
		}
		pulselight(c[0]);
	}
	
	function setWrap(type, width) {
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		if (type == 0) {
			c.removeClass('floatedcomponent');
			c.removeClass('floatedcomponentedit');
			c.css({ 'width': '', float : '' });
		} else {
			c.addClass('floatedcomponent');
			c.addClass('floatedcomponentedit');
			var floater = 'right';
			if (type == 1) floater = 'left';
			if (width == '') width = '0';
			c.css({ 'float': floater, 'width': width + 'px' });
		}
		pulselight(c[0]);
	}
	var prevtype = '';
	function setType(tag, type) {
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		
		// run an unwireup function if there is one
		if (c[0].ffComponentChangeType)
		    c[0].ffComponentChangeType(c[0]);
		    
		c.removeClass(componentTypes['ff'+prevtype]);
		c.addClass(componentTypes['ff' + type]);
		ffEventHandler.pushEvent('dominsert');
		prevtype = type;
		pulselight(c[0]);
	}
	
	
	html += '</div>';
	$('body').append(html);

	if (!flyouts) {
	    $('#ffToolbox>h2').hide();
	    if ($('#ffToolbox>a').length == 1) {
	        $('#ffToolbox').css('width', ($('#ffToolbox>a').outerWidth()+1));
	    }
	}

	$('select#ffTBCW, input#ffTBCWw').change(function() {
	    var val = document.getElementById('ffTBCWw').value;
	    if (val == '') val = '200';
	    setWrap(document.getElementById('ffTBCW').selectedIndex, val);
	    updateWrapDisplay();
	});
	
	updateWrapDisplay();
	$('select#ffTBCT').change(function() {
		setType('div', this.options[this.selectedIndex].value);
	});
	$('select#ffTBCC').change(function() {
		setContainer(this.options[this.selectedIndex].value);
	});
	liveChange('input#ffTBCWw', function() { setWrap(document.getElementById('ffTBCW').selectedIndex, document.getElementById('ffTBCWw').value); });
	
	// post back handling for everything except container change
	$('input#ffTBCH, select#ffTBCW, input#ffTBCWw, select#ffTBCT').change(function () {
		$.ajax({
			url: ffBaseURL + COMPONENT_HELPER_URL + selectedComponent,
			dataType: 'script',
			type: 'POST',
			data: { 'header': document.getElementById('ffTBCH').value, 'type' : document.getElementById('ffTBCT').options[document.getElementById('ffTBCT').selectedIndex].value, 'float_type' : document.getElementById('ffTBCW').selectedIndex, 'float_width' : document.getElementById('ffTBCWw').value },
			error: function(){ alert('Error saving component properties.  Check your internet connection and try refreshing the page.');  }			
         });
	});
	
	var txt = document.getElementById('ffTBCH');
	liveChange('input#ffTBCH', function() { 
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		var header = $('h2.componentheader', c);
		if (header.length == 0) {
			if (txt.value != '')
				$('.componentedit', c).after('<h2 class=\'componentheader\'>' + txt.value + '</h2>');
		} else {
			if (txt.value == '')
				header.remove();
			else
				header.text(txt.value);
		}
	});
	setupTextValidation('#ffTBCWw');
	
	var pos = {};
	var tb = $('div#ffToolbox');
	var origheight = tb.outerHeight();
	try {
	    origheight = $('div#ffToolbox h3').first()[0].offsetTop
	} catch (e) { }
	var scrollAdjust = false;
	var expanded = false;

	function getcatid(obj) {
	    var text = obj.text();
	    text = text.replace(/\s/g, "");
	    if (text.indexOf("(") > -1)
	        text = text.substring(0, text.indexOf("("));
	    return text;
	}
	
	function place() {
		if ($.browser.msie && ($.browser.version < 7)) {
			// very strange IE6 bug only moves on a dom change, so we alter by a random number
    	    tb.css({ 'right': Math.round(10 + Math.random()) + 'px', 'bottom': Math.round(10 + Math.random()) + 'px' });
		}
		else
			tb.css({ 'right': (10-$(window).scrollLeft()) + 'px', 'bottom': (10-$(window).scrollTop()) + 'px' });
	}
	
	$('a#ffTBCD').click(function() {
		if (PageMakeupDelete(selectedPage, document.getElementById('ffComponentEdit' + selectedComponent)))
			selectComponent(-1);
		return false;
	});
	
	$('a#ffTBCP').click(function() {
		ShowDialog('Admin/permissionsHtml.aspx?id=' + selectedComponent);
		return false;
	});
	
	$('a#ffTBCM').click(function(event) {
		ModifyComponent(document.getElementById('ffComponentEdit' + selectedComponent), ffGetData('ffComponent_' + selectedComponent, 'ffcomponenttype'), event);
		return false;
	});
	
	function toggle(force) {
		if (force) {
		    expanded = true;
			tb.css({ 'height': 'auto' });
		} else {
			if (!expanded)
				tb.css({ 'height': 'auto' });
			else
				tb.css({ 'height': origheight + 'px' });
			expanded = !expanded;

        }
        if (expanded) {
            $($("h2", tb)[0]).addClass('expanded');
        } else {
            $($("h2", tb)[0]).removeClass('expanded');
        }
		setTempCookie('ffToolboxOpen', expanded);
		if (!expanded)
			setTempCookie('ffToolbox', '');
	}
	
	$('div#ffToolbox h2').click(function() {
		toggle();
	});

	$('div#ffToolbox h3').click(function(ev) {
	    setTempCookie('ffToolbox', '');
	    var show = $(this).next();
	    $('div#ffToolbox div').each(function() {
	        if (($(this).prev().is(':visible')) && ($(this).get(0) == show.get(0)) && ((!$(this).is(':visible')) || ($(this).prev().data('ffforceshow')))) {
	            $(this).prev().data('ffforceshow', false);
	            $(this).prev().find('img')[0].src = 'Templates/acc-expanded.gif';
	            $(this).ffShow(100);
			setTempCookie('ffToolbox', getcatid($(this).prev()));
	        }
	        else {
	            $(this).prev().find('img')[0].src = 'Templates/acc-expand.gif';
	            $(this).hide(20);
	        }
	    });
	    if ($(this).is('h3#ffTBC') && componentDirty) {
	        if (selectedComponent == -1) {
	            $('h3#ffTBC + div > span:last').hide();
	            $('h3#ffTBC + div > span:first').text('Click an editable component to select it').show();
	        }
	        else selectComponentLive();
	    }
	});

	if ((document.compatMode == "BackCompat") || ($.browser.msie && ($.browser.version < 7))) {
		tb.css('position', 'absolute');
		scrollAdjust = true;
		$(function() { place(); });
		$(window).scroll(function() {
			place();
		});
	}
	
	var anyEditable = false;
	$('.component, .floatedcomponent').each(function() {
	    var id = $(this)[0].id.substring(12);
	    var thisEditable = document.getElementById('ffComponentEdit' + id);
	    if (thisEditable) anyEditable = true;
	    this.ffSelect = function(force) {
	        if (thisEditable) {
	            var newid = $(this)[0].id.substring(12);
	            if (force) selectedComponent = -1;
	            selectComponent(newid);
	        } else {
	            selectComponent(-1);
	        }
	    };
	}).click(function() {
	    this.ffSelect();
	});
    
	if (!anyEditable)
		$('h3#ffTBC').hide().next().hide();

    var sel = getCookie('ffToolbox');
	if (sel) {
	    $('div#ffToolbox h3').each(function() {
	        if (getcatid($(this)) == sel) { $(this).click(); }
	    }); }
		
	var open = getCookie('ffToolboxOpen');
	if (open == 'true')
	    toggle(true);
	else
	    tb.height(origheight + 'px');
		
	
		
	window.ComponentProperties = function(comp) {
		$('h3#ffTBC').data('ffforceshow', true);
		$('h3#ffTBC').trigger('click');
		if (!expanded)
			$('div#ffToolbox h2').trigger('click');
		
		highlightComponent(comp, false);
	};
}
function makeListExpandable(node) {
	$(function() {	
		var ul, toggleLink;
		$("li",node).each(
		function()
		{
			if(this.parentNode != node) return;
			ul = $("ul",this).get(0);
			if(ul)
			{
				$("ul",this).hide();
				toggleLink = document.createElement("a");
				toggleLink.href = "#";
				$(toggleLink).addClass("toggle");
				$(ul.parentNode.childNodes[0]).wrap(toggleLink);
				$("a.toggle", ul.parentNode).click(
					function()
					{
						$(">ul",this.parentNode).toggle(500);
						return false;
					}
				);
				makeListExpandable(ul);
			}
		}
	);
	});
}
function updateTargetContainer(page_id, container, forcerefresh) {
	ffOrderComponents();				
	 $.ajax({
		   url: "Admin/componentsMove.aspx",
		   dataType: 'script',
		  type: "POST",
		  data: 'page_id=' + page_id + '&container=' + $(container).get(0).id + '&' +$(container).sortable("serialize"),
		   error: function(){ alert('Error moving component.  Check your internet connection and try refreshing the page.'); }
	});
	if (forcerefresh) container.sortable('refresh');
	ffEventHandler.pushEvent('componentmoved');
}
function makeContainerSortable(page_id) {
    $(function() {
        // workaround IE overflow bug
        if ($.browser.msie) {
            $('.ff-container').each(function() {
                var p = this.parentNode;
                while (p && (p.tagName.toLowerCase() != 'body') && (p.tagName.toLowerCase() != 'html')) {
                    var overflow = getStyle(p, 'overflowY');
                    if ((overflow == 'auto') || (overflow == 'scroll')) {
                        p.style.position = 'relative';
                    }
                    p = p.parentNode;
                }
            });
        }

        $('.ff-container').sortable({ cursor: 'move', connectWith: $('.ff-container'), tree: true, revert: true, scroll: true, handle: '.ffDragHandle',
            tolerance: 'pointer',
            items: '>.component,>.floatedcomponent',
            placeholder: 'ff-containerplaceholder',
            start: function(e, ui) {
                $('.ff-container').css('border', 'dashed 2px #eeeeee');
                $('html').addClass('ff-container-sorting');
                highlight(ui.item.get(0), false, true); highlightLockDrag = true; ui.item.find("script").remove();
            },
            stop: function(e, ui) {
                $('.ff-container').css('border', '');
                $('html').removeClass('ff-container-sorting');
                highlightLockDrag = false;
            },
            over: function(e, ui) {
                $(this).css('border', 'dashed 2px #bbbbbb');
            },
            out: function(e, ui) {
                $(this).css('border', 'dashed 2px #eeeeee');
            },
            change: function(e, ui) {
                var floatsetting = ui.item.css('float').toUpperCase();
                if ((floatsetting == 'LEFT') || (floatsetting == 'RIGHT')) {
                    ui.placeholder.css('float', floatsetting);
                    ui.placeholder.css('width', ui.item.width() + 'px');
                    ui.placeholder.css('height', ui.item.height() + 'px');
                }
            },
            update: function(e, ui) {
                if (ui.sender || (ui.item.parent().get(0).id == $(this).get(0).id)) {
                    updateTargetContainer(page_id, this);
                    // force 'select' the new component to help the properties dialog
                    ui.item[0].ffSelect(true);
                    if (($.browser.msie) && ($.browser.version < 8)) {
                        // ie bug
                        ui.item[0].style.position = 'relative';
                        ui.item[0].style.position = '';
                    }
                }
            }
        });
    });
}
var ffEventHandler = {
    eventList: {},
    registerEvent: function(name, fn, runNow) {
        if (this.eventList[name]) {
            this.eventList[name].push(fn);
        } else {
            this.eventList[name] = [fn];
        }
        if (runNow) fn();
    },
    pushEvent: function(name) {
        var me = this;
        if (me.eventList[name]) {
            for (var i = 0; i < me.eventList[name].length; i++)
                me.eventList[name][i]();
        }
    }
};
        
function checkStyles(href) {
    for (var i = 0; i < document.styleSheets.length; i++) {
        var foundhref = document.styleSheets[i].href ? document.styleSheets[i].href.split('?')[0] : null;
        if (foundhref && foundhref.indexOf('://') == -1)
            foundhref = ffBaseURL + foundhref;
        if (foundhref && (foundhref.length >= href.length)) {
            if (foundhref.substring(foundhref.length - href.length).toUpperCase() == href.toUpperCase()) {
                return;
            }
		}
	}
	// not found, attach
	var l = this.document.createElement('link');
	l.setAttribute('type', 'text/css');
	l.setAttribute('href', href);
	l.setAttribute('rel', 'stylesheet');
	this.document.getElementsByTagName('head')[0].appendChild(l);   
}
function getStyle(o, prop){
	if (o.currentStyle) return o.currentStyle[prop]
	else if (document.defaultView && document.defaultView.getComputedStyle) return document.defaultView.getComputedStyle(o, "")[prop]
	else return o.style[prop];
}
function showEdit(id, over) {
	if (document.getElementById(id)) {
		document.getElementById(id).style.visibility = over ? '' : 'hidden';
	}
}
function setupComponentEdit(obj) {
    var p = $(obj).parent()[0];
    $(obj).parent().hover(function(e) { showComponentEdit(p, true); }, function(e) { showComponentEdit(p, false); });
    $(obj).hover(function() { highlight(p, true) }, function() { highlight(p, false); });
    $('.componentedithide', obj).click(function() {
        highlight(p, false, true);
        showComponentEdit(p, false, true);
    });
}
if (window.jQuery) {
    jQuery.fn.ffShow = function(timing) {
        return this.each(function() {
            $(this).show(timing, function() { $(this).css('zoom', ''); });
        });
    };
}
function setupSeeMore(container) {
    $(function() {
        var items = $('.see-more', container).length;
        var el = $("<a href='#' class='see-more-button'>See " + items + " more...</a>");
        el.click(function() {
            $('.see-more', container).ffShow(500);
            $(this).hide();
            return false;
        });
        $(container).append(el);
    });
}
function setupCollapsibleButtons(classname, firstsel) {
    $(function() {
        var selectedButton;
        var allitems = $('.' + classname + ' .collapsible');
        var btnclicker = function(ev) {
            var obj = this;
            if ($(ev.target).is('.collapsible-hide')) {
                obj = $(obj).data('ff-collapsible-btn');
                obj.disabled = true;
            }
            var linkedId = $(obj).attr('data-ff-linked-id');
            if (obj.disabled) {
                obj.disabled = false;
                $(obj).removeClass('depressed');
                if (linkedId) {
                    $('#' + linkedId).hide(200);
                } else {
                    $(obj).next().hide(200);
                }
            }
            else {
                obj.disabled = true;
                $(obj).addClass('depressed');
                if (linkedId) {
                    $('#' + linkedId).show(200);
                    $('#' + linkedId)[0].scrollIntoView();
                } else {
                    $(obj).next().show(200);
                    $(obj)[0].scrollIntoView();
                }
                if ($(obj).data('reveal')) {
                    $(obj).data('reveal')();
                }
            }
            return false;
        }
        allitems.each(function() {
            $(this).click(btnclicker);
            this.disabled = false;
            var that = this;

            var linkedId = $(that).attr('data-ff-linked-id');
            var $linkedItem;
            if (linkedId)
                $linkedItem = $('#' + linkedId);
            else
                $linkedItem = $(this).next()

            $('.collapsible-hide', $linkedItem).click(btnclicker).each(function() {
                $(this).data('ff-collapsible-btn', that);
            });
        });
        window.showPageEdit = function(on) {
            if (!on) {
                allitems.each(function() {
                    $('.collapsible-hide', $(this).next()).click();
                });
            }
        };
        if (firstsel) {
            var linkedId = $(allitems[0]).attr('data-ff-linked-id');

            $(allitems[0]).addClass('depressed');
            if (linkedId)
                $('#' + linkedId).show(200);
            else
                $(allitems[0]).next().show(200);
        }
    });
}
function showComponentEdit(pobj, show, noanim) {
    var obj = $('>.componentedit', pobj)[0];
    if (!obj) return;

    $obj = $(obj);
    $obj.stop(true, true);

    if (show) {
        //$obj.css('opacity', '0');
        $obj.css('display', 'inline');
    }

    var detectBug = (obj.ffComponentEditAbove === undefined);
    if (show) {
    	obj.ffComponentEditAbove = (obj.ffComponentEditAbove === undefined) ? true : obj.ffComponentEditAbove;
    }
   
    var marginTop = parseInt($obj.css('margin-top'));
    if (show) {
        // IE gap workaround
        var t = getTop(obj);
        var tp = getTop(pobj);
        var squeeze = t - tp + (obj.ffComponentEditAbove ? $obj.height() : 0);
        obj.style.marginTop = (marginTop - squeeze) + 'px';
        // detect IE zindex bug programmatically
        if (detectBug) {
            $obj.show();
            var rect = obj.getBoundingClientRect();
            var test = document.createElement('div');
            test.style.position = 'absolute';
            test.style.left = (rect.left + $(document).scrollLeft() - 10) + 'px';
            test.style.top = (rect.top + $(document).scrollTop()  - 10) + 'px';
            test.style.width = ((rect.right - rect.left) + 20) + 'px';
            test.style.height = ((rect.bottom - rect.top) + 20) + 'px';
            test.style.backgroundColor = 'white';
            test.style.zIndex = '500';
            document.body.appendChild(test);
            var el = document.elementFromPoint(rect.left + 20, rect.top + 20);
            if (!$.contains(obj, el)) {
                // we've found the bug, they are stacked wrongly
                obj.ffComponentEditAbove = false;
                squeeze = t - tp + (obj.ffComponentEditAbove ? $obj.height() : 0);
                obj.style.marginTop = (marginTop - squeeze) + 'px';
                $obj.addClass('componenteditovertop');
            }
            document.body.removeChild(test);

            $obj.css({ 'opacity': 0 });
        
        }
    }

    var animtime = (noanim) ? 0 : 500;

    if (!show) {
        $obj.animate({ 'opacity': 0 }, animtime, function() { $(this).hide(); });
    }
    else {
        $obj.animate({ 'opacity': 1.0 }, animtime);
    }
    
}

function isChildOf(parent, child) {
	if (parent == child) return false;
      
	while (child && child != parent)
		child = child.parentNode;

   return child == parent;
}
function getEventTarget(e) {
   if (e.target) {
      return e.target;
   } else if (e.srcElement) {
      return e.srcElement;
   }
   return null;
}
function getComponentIdFromElement(obj) {
	var id = -1;
	var i = 0;
	while ((i < 10) && obj.parentNode) {
		if (obj.id.substring(0, 15) == 'ffComponentEdit') {
			id = obj.id.substring(15);
			break;
		}
		obj = obj.parentNode;
		i++;
	}
	return id;
}
function highlightComponent(obj, show) {
	var id = getComponentIdFromElement(obj);
	if (id > -1) highlight(document.getElementById('ffComponent_' + id), show);
}
function highlightPage(id, show) {
	highlight(document.getElementById('ffPage' + id), show);
}
function highlightComment(id, show) {
    highlight(document.getElementById('ffComment' + id), show);
}
function highlightSiteLogo(show) {
    highlight(document.getElementById('ffSiteLogo'), show);
}
function createAjax() {
	if(typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
            var aVersions =
               [
                "MSXML2.XmlHttp.5.0",
                "MSXML2.XmlHttp.4.0",
                "MSXML2.XmlHttp.3.0",
                "MSXML2.XmlHttp",
                "Microsoft.XmlHttp"
					];
           for(var i = 0; i < aVersions.length; i++)
           {
              try
           {
              var oXhr = new ActiveXObject(aVersions[i]);
              return oXhr;
           }
              catch(oError) {}
           }
            
            return null;
      }
      else
         return null;
 }
var ffDeleteObj = null;
function ffMovedComponent(id, direction) {
	location.reload();
}
var ffBlogPageData = new Object();
function ffBlogPage(id, pageid) {
	for (tag in ffBlogPageData[''+id]) {
		for (var i = 0; i < ffBlogPageData[''+id][tag].length; i++)
			xBrowserGetElement(ffBlogPageData[''+id][tag][i]).style.display = (tag == pageid) ? '' : 'none';
	}
}
function ffReloadComponent(oldid, newid) {
	var ajax = createAjax();
	if (ajax != null) {
		ajax.open('GET', ffBaseURL + 'blank.aspx?id=' + newid + '&view=xml', true);
		ajax.onreadystatechange = function() {
		    if (ajax.readyState == 4) {
		        if ((ajax.status >= 200) && (ajax.status < 300)) {
				
		            if (ajax.responseXML.getElementsByTagName('component').length > 0) {
				var html = ajax.responseXML.getElementsByTagName('component')[0].firstChild.nodeValue;
				if (html.toUpperCase().indexOf('<SCRIPT') != -1) {
					location.reload();
					return;
				}
		                var editNode;
		                var headerNode;
		                var inplace = true;
		                if (savedNodes) {
		                    for (var i = 0; i < savedNodes.length; i++) {
		                        if (savedNodes[i].id == 'ffComponentEdit' + oldid)
		                            editNode = savedNodes[i];
		                        else if (savedNodes[i].className == 'componentheader')
		                            headerNode = savedNodes[i].cloneNode(true);
		                    }
		                } else {
		                    inplace = false;
		                    if (!highlightObj) highlightObj = document.getElementById('ffComponent_' + oldid);
		                    for (var i = 0; i < highlightObj.childNodes.length; i++) {
		                        if (highlightObj.childNodes[i].id == 'ffComponentEdit' + oldid) {
		                            editNode = highlightObj.childNodes[i];
		                        }
		                        else if (highlightObj.childNodes[i].className == 'componentheader')
		                            headerNode = highlightObj.childNodes[i].cloneNode(true);
		                    }
		                }
		                var newEditNode = editNode.cloneNode(true);
		                newEditNode.id = 'ffComponentEdit' + newid;
		                highlightObj.innerHTML = html;

		                if (headerNode) {
		                    if (highlightObj.firstChild)
		                        highlightObj.insertBefore(headerNode, highlightObj.firstChild);
		                    else
		                        highlightObj.appendChild(headerNode);
		                }

		                if (highlightObj.firstChild)
		                    highlightObj.insertBefore(newEditNode, highlightObj.firstChild);
		                else
		                    highlightObj.appendChild(newEditNode);

		                // insert the helper span as well
		                highlightObj.insertBefore(document.createElement('span'), highlightObj.firstChild);
		                setupComponentEdit(newEditNode);
		                ffEventHandler.pushEvent('dominsert');
		                highlightObj.id = 'ffComponent_' + newid;
		                // 'select' the new component to help the properties dialog
		                if (highlightObj.ffSelect)
		                    highlightObj.ffSelect();
		                if (inplace) {
		                    highlightLock = false;
		                    showComponentEdit(highlightObj, false);
		                    highlight(highlightObj, false);
		                } else {
		                    HideDialog();
		                }
		            }
		        }
		        else
		            location.reload();
		    } else return false;
		}
		ajax.send(null);
	} else {
		location.reload();
	}
}
function ffScrollTicker(id) {

	var div = document.getElementById('ffTickerContents' + id);
	if (div) {
		if (div.style.left == '') {
			div.style.visibility = '';
			div.style.left = document.getElementById('ffTickerFrame' + id).offsetWidth + 'px';
			div.style.width = document.getElementById('ffTickerSpan' + id).offsetWidth + 'px';
		}
		var left = parseInt(div.style.left);
		left -= 1;
		if (left < -div.offsetWidth) {
			left = document.getElementById('ffTickerFrame' + id).offsetWidth;;
		}
		div.style.left = left + 'px';
	}

}
function ffOrderComponents() {
	$('.ff-container').each(function() {
		$(this).children(':even').removeClass('even').addClass('odd');
		$(this).children(':odd').removeClass('odd').addClass('even');
	});		
}
function ffDeletedComponent(id) {
	deleteAnim(document.getElementById('ffComponent_' + id), ffOrderComponents);
}
function ffDeletedComment(id) {
    if ($('.forumlist').length > 0) {
        location.hash = '';
        location.reload();
    }
    $('#ffComment' + id).hide(1000);
    if (document.getElementById('ffComment' + id + 'R')) {
        $('#ffComment' + id + 'R').hide(1000);
    }
}
function deleteAnim(obj, fn) {
	if (!obj) { obj = ffDeleteObj; }
	if (ffDeleteObj == null) {
		//alert('constructing');
		ffDeleteObj = obj;
		obj.style.height = obj.offsetHeight + 'px';
		obj.style.overflow = 'hidden';
		//alert('hi');
		obj.heightStep = Math.round(obj.offsetHeight / 20);
		//alert(obj.heightStep);
	}
	var height = parseInt(obj.style.height);
	height -= obj.heightStep;
	if (height <= 0) {
		obj.parentNode.removeChild(obj);
		ffDeleteObj = null;
		if (fn) fn();
	} else {
		obj.style.height = height + 'px';
		setTimeout(function() { deleteAnim(obj, fn) }, 50);
	}
}
function highlight(obj, show, noanimate) {

    ffLog('highlight ' + show);
    
	if (highlightLockDrag)
		return;
		
	// check the whole DOM is ready in IE (avoids IE bug)
	if(typeof document.documentElement.doScroll != 'undefined') {
	try {	
		document.documentElement.doScroll('left');
	} catch (e) {
		return;
    } 
    }

    highlightDirection = show;
   
	if (!show && !highlightLock) {
	    try { clearTimeout(highlightTimer); } catch (e) {}
		highlightAnimation(false, noanimate);
		highlightObj = null;
		return;
	} else if (!highlightLock) {
		try {
			clearTimeout(highlightTimer);
		} catch(e) {}
	}
	if (!show)
	    return;

    highlightObj = obj;

    var top = getTop(obj); var left = getLeft(obj); var width = $(obj).outerWidth(true); var height = $(obj).outerHeight(true);

	if (obj.id.substring(0,6) == 'ffPage') {
		// special width calculation
		var editicons = document.getElementById('ffPageEdit' + obj.id.substring(6));
		if (editicons) {
		var specleft = getLeft(editicons) - left;
		if ((specleft + editicons.offsetWidth) > width) {
			width = specleft + editicons.offsetWidth;
		} }
	}

	var bodyHeight = ffGetDimensions().pageHeight;
	var bodyWidth = ffGetDimensions().pageWidth - 1;


	appendMaskingDiv(createMaskingDiv(0, 0, bodyWidth, top, 'above'));
	appendMaskingDiv(createMaskingDiv(top+height, 0, bodyWidth, bodyHeight-(top+height), 'below'));
	appendMaskingDiv(createMaskingDiv(top, 0, left, height, 'left'));
	appendMaskingDiv(createMaskingDiv(top, width+left, bodyWidth-(width+left), height, 'right'));
	
	highlightAnimation(true, noanimate);

}
function SendFeedback() {
	ShowDialog('Admin/sendfeedback.aspx?url=' + escape(location.href));
}
function SendFeedback(page_id) {
    ShowDialog('Admin/sendfeedback.aspx?url=' + escape(location.href) + '&page_id=' + page_id);
}
function ShowImpersonate() {
    ShowDialog('Admin/impersonate.aspx');
}
function ffGetScrollTop () {
    //if (document.body.parentNode.scrollTop) return document.body.parentNode.scrollTop; else	return document.body.scrollTop;
    return $(window).scrollTop();
}

function ffGetScrollLeft() {
    //if (document.body.parentNode.scrollLeft) return document.body.parentNode.scrollLeft; else	return document.body.scrollLeft;
    return $(window).scrollLeft();
}

function ffGetDimensions() {
	var ret = {};
	if (document.compatMode == "BackCompat") {
		ret.viewportWidth = document.body.clientWidth;
		ret.viewportHeight = document.body.clientHeight;
		ret.pageHeight = Math.max(document.body.scrollHeight, document.body.clientHeight);
		ret.pageWidth = Math.max(document.body.scrollWidth, document.body.clientWidth);
	
	} else {
	if (document.documentElement && document.documentElement.clientHeight) {
		ret.viewportWidth = document.documentElement.clientWidth;
		ret.viewportHeight = document.documentElement.clientHeight;
	}
	else {
		ret.viewportWidth = document.body.clientWidth;
		ret.viewportHeight = document.body.clientHeight;
	}
	if (document.body.scrollHeight > document.body.offsetHeight) {
		ret.pageWidth = document.body.scrollWidth;
		ret.pageHeight = document.body.scrollHeight;
	} else {
		ret.pageWidth = document.body.offsetWidth;
		ret.pageHeight = document.body.offsetHeight;
	}
	if (document.documentElement.scrollHeight > document.documentElement.offsetHeight) {
		ret.pageWidth = document.documentElement.scrollWidth;
		ret.pageHeight = document.documentElement.scrollHeight;
	} else {
		ret.pageWidth = document.documentElement.offsetWidth;
		ret.pageHeight = document.documentElement.offsetHeight;
	}
}

/* IE 8 fixes */

    if (((ret.pageWidth - ret.viewportWidth) < 5) && ((ret.pageWidth - ret.viewportWidth) > 0)) ret.pageWidth = ret.viewportWidth;
    if (((ret.pageHeight - ret.viewportHeight) < 5) && ((ret.pageHeight - ret.viewportHeight) > 0)) ret.pageHeight = ret.viewportHeight;

	if (ret.pageWidth < ret.viewportWidth) ret.pageWidth = ret.viewportWidth;
	if (ret.pageHeight < ret.viewportHeight) ret.pageHeight = ret.viewportHeight;

	return ret;
}

function ffInplaceHeightHint(height, fn) {
	if ((!dialogNode) || (dialogNode.style.display == 'none')) return;
	var newheight = 300;
	var offset = 50;
	if (height > newheight) newheight = Math.min(height, (ffGetDimensions().viewportHeight+ffGetScrollTop()) - getTop(dialogNode));
	var node = highlightObj;
	dialogNode.height = newheight;
	highlight(highlightObj, false, true);
	highlight(node, true, true);
	if (fn) fn();
}

var highlightObj;
var highlightMaxOpacity = 0.2;
var highlightHelperObj;
var highlightLock = false;
var highlightLockDrag = false;

function highlightAnimation(forward, noanimate) {

	if (noanimate) {
	    if (forward) {
	        $('#ffMaskabove, #ffMaskbelow, #ffMaskleft, #ffMaskright').css('opacity', highlightMaxOpacity);
	    } else {
	        if (document.getElementById('ffMaskabove') && document.getElementById('ffMaskbelow') && document.getElementById('ffMaskleft') && document.getElementById('ffMaskright')) {
	            document.body.removeChild(document.getElementById('ffMaskabove'));
	            document.body.removeChild(document.getElementById('ffMaskbelow'));
	            document.body.removeChild(document.getElementById('ffMaskleft'));
	            document.body.removeChild(document.getElementById('ffMaskright'));
	        }
	        return;
	    }
	} else {
	    // use jquery instead now
	    $('#ffMaskabove, #ffMaskbelow, #ffMaskleft, #ffMaskright').stop(true, true).animate({ 'opacity': (forward ? highlightMaxOpacity : 0) }, 500, function() {
	        if (!forward) {
	            $('#ffMaskabove, #ffMaskbelow, #ffMaskleft, #ffMaskright').remove();
	        }
	    });    
	}



}
function getOpacity(obj) {
	try {
		return parseFloat(obj.style.opacity);
	} catch (err) { return 1; }
}
function setOpacity(obj, opacity) {
    if (!obj) return;
	if (obj.style.display.toLowerCase() == 'none') obj.style.display = '';
	if (opacity == null) { obj.style.opacity = ''; obj.style.filter = ''; return; }
	obj.style.opacity = opacity;
	obj.style.filter = 'alpha(opacity=' + (opacity*100) + ')';
}
function createMaskingDiv(top, left, width, height, name) {
	if (top < 0) top = 0;
	if (left < 0) left = 0;
	if (width < 0) width = 0;
	if (height < 0) height = 0;
	var mask = document.getElementById('ffMask' + name);
	if (!mask) mask = document.createElement('div');
	mask.id = 'ffMask' + name;
	mask.style.width = width + 'px';
	mask.style.height = height + 'px';
	mask.style.backgroundColor = 'black';
	mask.style.position = 'absolute';
	mask.style.opacity = '0';
	mask.style.filter = 'alpha(opacity=0)';
	mask.style.left = left + 'px';
	mask.style.top = top + 'px';
	mask.style.zIndex = 500;
	//mask.style.display = 'none';
	return mask;
}
function appendMaskingDiv(div) {
	if (!document.getElementById(div.id)) 
		document.body.appendChild(div);
}
function ffGalleryShowFullscreen(id) {
	var height = screen.availHeight * 0.95;
	var width = screen.availWidth * 0.95;
	var top = Math.round((screen.availHeight/2) - (height/2));
	var left = Math.round((screen.availWidth/2) - (width/2));
	var url = "";
	if (ffBaseURL) url = ffBaseURL;
	var newWindow = window.open(url + "slideshow.aspx?id=" + id, "slideshow", "status=no,directories=no,toolbar=no,scrollbars=yes,resizable=yes,location=no,menu=no,width=" + width + ",height=" + height + ",screenX=" + left + ",screenY=" + top + ",top=" + top + ",left=" + left);
	newWindow.focus();
}
function addResizeEvent(func) {	
	var oldonresize = window.onresize;
	if (typeof window.onresize != 'function'){
    	window.onresize = func;
	} else {
		window.onresize = function(){ oldonresize(); func(); };
	}
}
addResizeEvent(function() {
    if (maskNode) {

        var bodywidth = ffGetDimensions().pageWidth;
        var bodyheight = ffGetDimensions().pageHeight;
        maskNode.style.height = bodyheight + 'px';
        maskNode.style.width = bodywidth + 'px';
        if (highlightObj) {
            highlight(highlightObj, false, true);
            highlight(highlightObj, true, true);
        }
        if (dialogNode && dialogNode.parentNode == document.body) {
            var height = parseInt(dialogNode.style.height);
            var width = parseInt(dialogNode.style.width);
            var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight / 2) - (height / 2));
            var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth / 2) - (width / 2));
            dialogNode.style.left = left + 'px';
            dialogNode.style.top = top + 'px';
        } if (dialogThrobberNode) {
            var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight / 2) - (75 / 2));
            var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth / 2) - (75 / 2));
            dialogThrobberNode.style.left = left + 'px';
            dialogThrobberNode.style.top = top + 'px';
        }

    }

});
function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){ oldonload(); func(); };
	}
}

function ffSlideShow(container, imageSrc, imageDesc, params) {
	this.container = container;
	this.params = params;
	if (this.params.fullScreen) {
		var min = ffGetDimensions().viewportHeight;
		if (ffGetDimensions().viewportWidth < min)
			min = ffGetDimensions().viewportWidth;
		this.height = (parseInt(min*0.95) - 100);
		this.width = this.height;
		this.container.style.height = this.height + 'px';
		this.container.style.width = this.width + 'px';
		addResizeEvent(function() { location.reload(); });
	} else {
		this.height = this.container.offsetHeight;
		this.width = this.container.offsetWidth;
	}
	this.params.descs = (imageDesc) ? true : false;
	this.panelHeight = 40;
	this.idx = 0;
	this.imgIdx = 0;
	this.moveauto = false;
	this.animTimer = false;
	this.showPanelAnim = false;
	this.animProgress = 0;
	this.imagesList = new Array(imageSrc.length);
	this.hasDescs = false;
	for (var i = 0; i < imageSrc.length; i++) {
		if (imageDesc[i]) this.hasDescs = true;
		if (params.ratio == '' || this.params.fullScreen) {
			this.imagesList[i] = { u: imageSrc[i] + '&thumb=' + this.width, t: (imageDesc[i]) ? imageDesc[i] : ''};
		} else {
			this.imagesList[i] = { u: imageSrc[i] + '&pa=on&height=' + this.height + '&width=' + Math.round(this.height*params.ratio), t: (imageDesc[i]) ? imageDesc[i] : ''};
		}
	}
	for (var i = 0; i < this.imagesList.length; i++) {
		var t = new Image(this.width, this.height);
		t.src = this.imagesList[i].u;
	}
}

ffSlideShow.prototype.addEvent = function(elem, evt, fn) {
	if (elem.addEventListener) {
	 elem.addEventListener(evt, fn, false);
      } else if (elem.attachEvent) {
	 elem.attachEvent('on' + evt, fn);
      }
};

ffSlideShow.prototype.showPanel = function(on) {
	if (this.showPanelAnim) window.clearInterval(this.showPanelAnim);
	this.showPanelAdmin = false;
	this.panel.style.visibility = '';
	var ffs = this;
	this.showPanelAnim = window.setInterval(function() { ffs.showPanelAnimStep(on); }, 50);
};

ffSlideShow.prototype.showPanelAnimStep = function(on) {
	var top = parseInt(this.panel.style.top);
	if (on) {
		if (top <= (this.height - this.panelHeight)) {
			window.clearInterval(this.showPanelAnim);
			this.showPanelAnim = false;
		} else {
			top = top - (this.panelHeight / 10);
			this.panel.style.top = top + 'px';
		}
	} else {
		if (top >= this.height) {
			window.clearInterval(this.showPanelAnim);
			this.showPanelAnim = false;
		} else {
			top = top + (this.panelHeight / 10);
			this.panel.style.top = top + 'px';
		}
	}
};

ffSlideShow.prototype.showPanel2 = function(on) {
	this.panel2.style.visibility = (on) ? 'visible' : 'hidden';
};

ffSlideShow.prototype.move = function(dirn) {
	var ffs = this;
	if (this.moveauto) window.clearTimeout(this.moveauto);
	if (!this.animTimer) {
	var newidx = this.idx + dirn;
	if (newidx < 0)
		newidx = this.imagesList.length - 1;
	else if (newidx >= this.imagesList.length)
		newidx = 0;
	this.setImage(newidx);
	}
	else {
		this.moveauto = window.setTimeout(function() { ffs.move(1); }, 100); 
	}
};

ffSlideShow.prototype.setImage = function(idx) {
	this.title.innerHTML = this.imagesList[idx].t;
	if (this.imgIdx == 0) this.img[1].src = this.imagesList[idx].u;
	else this.img[0].src = this.imagesList[idx].u;
	this.idx = idx;
};

ffSlideShow.prototype.imgLoad = function(idx) {
	if (idx != this.imgIndex) {
		this.animStart();
	}
}

ffSlideShow.prototype.animStep = function() {

	// 1 is fade
	if (this.params.animType == '1') {
		if (this.imgIdx == 0)
			setOpacity(this.img[1], this.animProgress / 100);
		else
			setOpacity(this.img[1], 1-(this.animProgress / 100));
		if (this.animProgress == 0) {
			this.img[1].style.visibility = '';
		}
		this.animProgress = this.animProgress + 1;
	// 2 is box
	} else if (this.params.animType == '2') {
		var height = ((this.animProgress) / 100) * this.height;
		var width = ((this.animProgress) / 100) * this.width;
		if (this.imgIdx == 1) {
			height = this.height - height;
			width = this.width - width;
		}
		this.img[1].style.height = height + 'px';
		this.img[1].style.width = width + 'px';
		if (this.animProgress == 0) {
			this.img[1].style.visibility = '';
		}
		this.animProgress = this.animProgress + 1;
	} else {
		if (this.imgIdx == 0)
			this.img[1].style.visibility = '';
		else
			this.img[1].style.visibility = 'hidden';
		this.animProgress = 101;
	}

	if (this.animProgress > 100) {
		if (this.imgIdx == 0) { this.imgIdx = 1; } else { this.imgIdx = 0; }
		this.animStop();
	}
};

ffSlideShow.prototype.animStart = function() {
	if (this.animTimer) window.clearInterval(this.animTimer);
	this.animProgress = 0;
	var ffs = this;
	this.animTimer = window.setInterval(function() { ffs.animStep(); }, 10);
}

ffSlideShow.prototype.animStop = function() {
	if (this.animTimer)  {
		window.clearInterval(this.animTimer);
		this.animTimer = false;
		var ffs = this;
		if (this.params.autoSeconds > 0) {
			if (this.moveauto) window.clearTimeout(this.moveauto);
			this.moveauto = window.setTimeout(function() { ffs.move(1); }, this.params.autoSeconds * 1000); 
		}
	}
}

ffSlideShow.prototype.stylePanel = function(pan) {
	pan.style.backgroundColor = 'black';
	pan.style.color = 'white';
	pan.style.position = 'absolute';
	setOpacity(pan, 0.5);
}

ffSlideShow.prototype.render = function(fullScreenFn) { 
	var ffs = this;
	this.container.style.position = 'relative';
	this.container.style.overflow = 'hidden';
	this.panel = document.createElement('div');
	this.stylePanel(this.panel);
	this.panel.style.top = (this.height) + 'px';
	this.panel.style.height = this.panelHeight + 'px';
	this.panel.style.width = this.width + 'px';
	this.panel.className = 'ffSlideShowPanel';
	this.container.insertBefore(this.panel, this.container.childNodes[0]);
	if (this.params.showFullScreen && !this.params.fullScreen) {
		this.panel2 = document.createElement('div');
		this.panel2.style.textAlign = 'right';
		this.stylePanel(this.panel2);
		this.panel2.style.width = this.width + 'px';
		this.panel2.style.height = '1.5em';
		this.panel2.innerHTML = 'Show fullscreen';
		this.panel2.style.cursor = 'pointer';
		this.addEvent(this.panel2, 'click', fullScreenFn);
		this.container.insertBefore(this.panel2, this.container.childNodes[0]);
	}
	this.showPanel(this.params.fullScreen);
	if (!this.params.fullScreen && this.params.showFullScreen) {
		this.showPanel2(false);
	}
	if (this.params.navControls) {
	this.left = document.createElement('div');
	this.left.style.cssFloat = 'left';
	this.left.style.styleFloat = 'left';
	this.left.style.width = '26px';
	this.left.style.height = '26px';
	this.left.style.marginTop = '5px';
	this.left.style.backgroundImage = 'url(Templates/left.png)';
	this.left.style.cursor = 'pointer';
	this.addEvent(this.left, 'click', function() { ffs.move(-1); });
	this.panel.appendChild(this.left);
	this.right = document.createElement('div');
	this.right.style.cssFloat = 'right';
	this.right.style.styleFloat = 'right';
	this.right.style.width = '26px';
	this.right.style.height = '26px';
	this.right.style.marginTop = '5px';
	this.right.style.backgroundImage = 'url(Templates/right.png)';
	this.right.style.cursor = 'pointer';
	this.addEvent(this.right, 'click', function() { ffs.move(1); });
	this.panel.appendChild(this.right);
	}
	this.title = document.createElement('div');
	this.title.style.padding = '10px';
	this.title.innerHTML = this.imagesList[0].t;
	this.title.style.textAlign = 'center';
	this.panel.appendChild(this.title);
	if (!this.params.fullScreen) {
		if (this.params.navControls || this.hasDescs) {
			this.addEvent(this.container, 'mouseover', function() { ffs.showPanel(true); });
			this.addEvent(this.container, 'mouseout', function() { ffs.showPanel(false); });
		}
		if (this.params.showFullScreen) {
			this.addEvent(this.container, 'mouseover', function() { ffs.showPanel2(true); });
			this.addEvent(this.container, 'mouseout', function() { ffs.showPanel2(false); });
		}
	}
	this.img = [ this.container.getElementsByTagName('img')[0], document.createElement('img') ];
	this.img[0].width = this.width;
	this.img[0].height = this.height;
	this.img[1].width = this.width;
	this.img[1].height = this.height;
	this.img[1].style.position = 'absolute';
	this.img[1].style.visibility = 'hidden';
	this.addEvent(this.img[1], 'load', function() { ffs.imgLoad(1); });
	this.addEvent(this.img[0], 'load', function() { ffs.imgLoad(0); });
	this.container.insertBefore(this.img[1], this.container.childNodes[0]);
	if (this.params.autoSeconds > 0) {
		this.moveauto = window.setTimeout(function() { ffs.move(1); }, this.params.autoSeconds * 1000); 
	}

};

var ffGalleryTableLoaded = false;
function ffGalleryLoadFancybox() {
    if (!ffGalleryTableLoaded && (document.compatMode != "BackCompat")) {
        ffLoadScript(ffBaseURL + 'Templates/lib/fancybox/jquery.fancybox-1.3.1.pack.js', 'head', function() { 
		$(function() { $('.ffGalleryImg').fancybox({ 'type': 'image' }); });
        });
        checkStyles(ffBaseURL + 'Templates/lib/fancybox/jquery.fancybox-1.3.1.css');
        ffGalleryTableLoaded = true;
    }
};

function ffGalleryLayoutTable(id, cols, rows, size, galimages, descs, controls) {

    size *= 0.5;
	var pages = Math.ceil(galimages.length/(cols*rows));
	document.write("<table width='100%' class='thumbnailtable' cellpadding=5 cellspacing=3>");
	if ((pages > 1) && controls) {
		document.write("<tr><td colspan=" + cols + " class='thumbnailstop'><center><span id='ffGallery" + id + "_top'>Page 1/" + pages + "</span></center></td></tr>");
	}
	for (var i = 0; i < rows; i++) {
		document.write("<tr>");
		var stop = false;
		for (var j = 0; j < cols; j++) {
		
				if (galimages[(cols*i)+j] == null) {
					document.write("<td>&nbsp;</td>");
					stop = true;
				}
				else {
					document.write("<td><center><a href=\"" + galimages[(cols*i)+j] + "\" target='_blank' class='ffGalleryImg' rel='ff-gallery-" + id + "' ><img width=" + size + "height=" + size + " border=0 id='ffGallery" + id + "_" + ((cols*i)+j) + "_img' src=\"" + galimages[(cols*i)+j] + "&thumb=" + size + "\"></a>");
					if (descs.length > 0)
						document.write("<div id='ffGallery" + id + "_" + ((cols*i)+j) + "_div' class='thumbnaildesc' style='text-align: center'>" + descs[(cols*i)+j] + "</div>");
					document.write("</center></td>");
				}
		}
		document.write("</tr>");
		if (stop) break;
	}
	if ((pages > 1) && (controls)) {
		document.write("<tr><td colspan=" + cols + "><center><a href='javascript:ffGalleryRelativePage(" + id + ",-1)'>&lt; Back</a> ");
		for (var k = 0; k < pages; k++) {
			document.write("<a href='javascript:ffGalleryPage(" + id + "," + (k) + ")'>" + (k+1) + "</a> ");
		}
		document.write("<a href='javascript:ffGalleryRelativePage(" + id + ",1)'>Forward &gt;</a></center></td></tr>");
	}
	document.write("</table>");
//	if (pages > 1)
//		ffGalleryPagePreload(id, 1);

	ffGalleryLoadFancybox();
}

function ffGalleryPage(id, page) {

	if (page < 0) return;
	var galimages = window["ffGallery" + id + "Images"];
	var descs = window["ffGallery" + id + "Descs"];
	var cols = window["ffGallery" + id + "Cols"];
	var rows = window["ffGallery" + id + "Rows"];
	var size = window["ffGallery" + id + "Size"] * 0.5;
	var pages = Math.ceil(galimages.length/(cols*rows));
	if (page >= pages) return;
	var startrow = page*rows;
		
	for (var i = startrow; i < startrow+rows; i++) {
		for (var j = 0; j < cols; j++) {
		
			if (galimages[(cols*i)+j] != null) {
				if (descs.length > 0)
					xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_div").innerHTML = descs[(cols*i)+j];
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").src = "Templates/pixel.gif";
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").src = galimages[(cols*i)+j] + "&thumb=" + size;
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").parentNode.href = galimages[(cols*i)+j];
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").parentNode.style.visibility = "";
			}
			else {
				if (descs.length > 0)
					xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_div").innerHTML = "";
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").parentNode.style.visibility = "hidden";
			}
		}
	}
	
	window["ffGallery" + id + "Page"] = page;
	xBrowserGetElement("ffGallery" + id + "_top").innerHTML = "Page " + (page+1) + "/" + pages;
//	if (page < (pages - 1))
//		ffGalleryPagePreload(id, page + 1);

}

function ffGalleryRelativePage(id, relpage) {
	ffGalleryPage(id, window["ffGallery" + id + "Page"] + relpage);
}
function ShowDialog(url) {
	ShowDialog(url, "no");
}
function IsInProblematicOverflowedDiv(t) {
    if (window.navigator.userAgent.indexOf('MSIE') == -1) return false;
    if (document.compatMode != "BackCompat") return false;
    var overflowedDivs = false;
    while (t && (t.tagName.toUpperCase() != 'BODY') && (t.tagName.toUpperCase() != 'HTML')) {
        if (t.style.overflow != '') {
            overflowedDivs = true;
            break;
        }
        t = t.parentNode;
    }
    return overflowedDivs;
}
function ShowDialog(url, scrollbars, height, width, inplace) {
	if (ffBaseURL) url = ffBaseURL + url;
	if (highlightObj) {
	    var t = highlightObj;
	    var overflowedDivs = IsInProblematicOverflowedDiv(t);
		if (overflowedDivs) {
			inplace = false;
		}
	}
	
	if (dialogNode) {
		try	{ document.body.removeChild(dialogNode); } catch (e) {  };
    }

    $('.componentedit').hide();
	
	var id = Math.random();
	
	if (inplace)
		showPageEdit(false);
	
	if (height == null) height = 500;
	if (width == null) width = 550;
	
	dialogNode = document.createElement('iframe');
	dialogNode.name = 'ffDialogNode' + id;
	dialogNode.id = 'ffDialogNode' + id;
	dialogNode.ffURL = url;
	dialogNode.setAttribute('scrolling', 'no');
	dialogThrobberNode = null;

	dialogNode.width = '100%';
	dialogNode.height = '100%';

	if (!inplace || !highlightObj) {

	    // now create a wrapper div
	    var iframe = dialogNode;
	    iframe.frameBorder = '0';
	    var wrapper = document.createElement('div');
	    wrapper.className = 'ff-dialog';
	    var close = document.createElement('span');
	    $(close).click(function() { HideDialog(); });
	    close.className = 'ff-dialog-close';
	    close.innerHTML = 'Close';
	    wrapper.appendChild(close);
	    wrapper.appendChild(dialogNode);
	    dialogNode = wrapper;
	    wrapper.ffIframe = iframe;
	
		var bodywidth = ffGetDimensions().pageWidth;
		var bodyheight = ffGetDimensions().pageHeight;
		maskNode = createMaskingDiv(0, 0, bodywidth, bodyheight, 'dialog');
		appendMaskingDiv(maskNode);
		
		var scrolltop = ffGetScrollTop();
		var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight/2) - (height/2));
		var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth/2) - (width/2));
		dialogNode.style.left = left + 'px';
		dialogNode.style.top = top + 'px';
		dialogNode.style.height = height + 'px';
		dialogNode.style.width = width + 'px';

		var throbber = true;

		if (navigator.appName == 'Microsoft Internet Explorer')
		    window.dialogThrobberInterval = setInterval(function() { if (iframe.contentWindow.document.body) { hideThrobber(); } }, 250);
		else {
		    iframe.setAttribute('onload', 'hideThrobber()');
		}
				
		dialogNode.dialogOpacity = 0;
		dialogNode.dialogTopStep = (height + top) / 25;

        if (throbber) {
            dialogThrobberNode = document.createElement('div');
            dialogThrobberNode.className = 'throbber';
		    document.body.appendChild(dialogThrobberNode);
		}

		document.body.appendChild(dialogNode);
		if (document.compatMode != 'BackCompat') {
		    if ($(dialogNode).draggable)
		        $(dialogNode).draggable({ iframeFix: true }).css('cursor', 'move');
		}
		ShowDialogFade();
		
	} else {
	
		var node = highlightObj;
		
		var offset = 50;

		var height = 300;
			
		dialogNode.setAttribute('height', height);
		dialogNode.setAttribute('width', '100%');
		dialogNode.setAttribute('border', '0');
		dialogNode.setAttribute('frameborder', '0');

		//highlight(highlightObj, false, true);		
		savedNodes = new Array();
		var i = 0;
		while (node.childNodes.length > 0) {
			savedNodes[i] = node.childNodes[0];
			node.removeChild(node.childNodes[0]);
			i++;
		}
		node.appendChild(dialogNode);

		highlight(node, true, true);
	
	
	}

	frames['ffDialogNode' + id].location.href = url;
	highlightLock = true;

}

function ShowDialogResize(width, height) {
    if (dialogNode) {
        var scrolltop = ffGetScrollTop();
        var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight / 2) - (height / 2));
        var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth / 2) - (width / 2));
        dialogNode.style.left = left + 'px';
        dialogNode.style.top = top + 'px';
        dialogNode.style.height = height + 'px';
        dialogNode.style.width = width + 'px';
    }
}

var dialogNode;
var dialogThrobberNode;
var maskNode;
var savedNodes;

function hideThrobber() {
    if (dialogThrobberNode) document.body.removeChild(dialogThrobberNode);
    if (window.dialogThrobberInterval) clearInterval(window.dialogThrobberInterval);
    dialogThrobberNode = null;
}

function ShowDialogFade(reverse) {
	/*if ((!reverse && (dialogNode.dialogOpacity >= 50)) || (reverse && (dialogNode.dialogOpacity <= 0))) {
		ShowDialogFadeFinish(reverse);
	} else {
		dialogNode.dialogOpacity = (reverse) ? dialogNode.dialogOpacity - 10 : dialogNode.dialogOpacity + 10;
	    setOpacity(maskNode, dialogNode.dialogOpacity/100);
		
		window.setTimeout('ShowDialogFade(' + reverse + ')', 10);
	}*/
    $(maskNode).stop(true, true).animate({ 'opacity': (reverse ? 0 : 0.5) }, 500, function() { ShowDialogFadeFinish(reverse); });
}
function ShowDialogFadeFinish(reverse) {
    if (reverse) {
        document.body.removeChild(maskNode);
        if (dialogThrobberNode != null)
            document.body.removeChild(dialogThrobberNode);
        if (dialogNode) {
            try { dialogNode.parentNode.removeChild(dialogNode); } catch (e) {}
        }
        try {
	        highlightLock = false;
		    highlight(highlightObj, false);
		} catch (e) { }
	} else {
		if (dialogNode.ffIframe && dialogNode.ffIframe.contentWindow.placeFocus) dialogNode.ffIframe.contentWindow.placeFocus();
		else if (dialogNode.contentWindow && dialogNode.contentWindow.placeFocus) dialogNode.contentWindow.placeFocus();
	}
}

function HideDialog(noremove) {

	if (dialogNode.parentNode == document.body) {
		dialogNode.style.display = 'none';
		ShowDialogFade(true);
		try {
			highlightLock = false;
			highlight(highlightObj, false);
		} catch (blah) {}
	} else {
		var node = highlightObj;
		highlightLock = false;
		highlight(highlightObj, false, true);
		node.removeChild(dialogNode);
		for (var i = 0; i < savedNodes.length; i++) {
			node.appendChild(savedNodes[i]);
		}
		node.editLock = false;
	}
}

function DeleteSection(id) {
	ShowDialog("Admin/sectionsDelete.aspx?id=" + id);
}

function ChangeLayout(id) {
	ShowDialog("Admin/pagesLayout.aspx?id=" + id);
}

function AddSection(id) {
	ShowDialog("Admin/sectionsModify.aspx?parent_id=" + id);
}

function AddToplevelSection(site_id) {
    ShowDialog("Admin/sectionsModify.aspx?site_id=" + site_id);
}


function ModifySection(id) {
	ShowDialog("Admin/sectionsModify.aspx?id=" + id);
}

function ModifyComponent(obj, type, event) {

	var id = getComponentIdFromElement(obj);
	if (id == -1) return;
	
	if (type == "html") {
		var url = "Admin/modifyHtml.aspx?id=" + id;
		
		var width = ffGetDimensions().viewportWidth - 120;
		var height = ffGetDimensions().viewportHeight - 120;
		var inplace = highlightObj && (highlightObj.offsetWidth > 700);
			
		if (event.ctrlKey) inplace = false;
	
		ShowDialog(url, "no", height, width, inplace);
	}

	else if (type == "RSS") {
		var url = "Admin/modifyNewsSummary.aspx?id=" + id;
		var width = 800;
		var height = 450;
		ShowDialog(url, "no", height, width);
	}

	else if (type == "progress") {
		ShowDialog("Admin/modifyProgressCheck.aspx?id=" + id);
	}

	else if (type == "question") {
		var url = "Admin/modifyQuestion.aspx?id=" + id;
		var width = 600;
		var height = 460;
		ShowDialog(url, "no", height, width);
	}

	else if (type == "calendar") {

		var url = "Admin/modifyCalendar.aspx?id=" + id;
		var width = 700;
		var height = 460;
		ShowDialog(url, "no", height, width);
    }

    else if (type == "contact") {

        var url = "Admin/modifyContact.aspx?id=" + id;
        var width = 600;
        var height = 410;
        ShowDialog(url, "no", height, width);
    }	
	
	else if (type == "gallery" || type == "resourcelist") {

		var url = "Admin/modifyGallery.aspx?id=" + id;
		var width = 700;
		var height = 450;
		ShowDialog(url, "no", height, width);

	}
	
	else if (type == "plugin") {

		var url = "Admin/modifyPluginComponent.aspx?id=" + id;
		var width = 550;
		var height = 350;
		ShowDialog(url, "no", height, width);

	}
	
}
function PageMakeupDelete(page, obj) {
	if (window.confirm("Are you sure you want to delete the selected component?")) {
		var id = getComponentIdFromElement(obj);
		if (id == -1) return;
		DoHiddenDialog("Admin/pageMakeupDelete.aspx?page_id=" + page + "&component_id="+ id);
	}
}
function PageMakeupFloat(obj) {
	var id = getComponentIdFromElement(obj);
	if (id == -1) return;
	ShowDialog('Admin/componentsFloat.aspx?id=' + id);
}
function PageMakeupMove(page_id, obj, up, e) {
	var id = getComponentIdFromElement(obj);
	if (id == -1) return;
	var dirn = up ? 'up' : 'down';
	var memobj = up ? pageMakeupMoveUpCounts : pageMakeupMoveDownCounts;
	if (memobj[id]) {
		memobj[id] = memobj[id]+1;
	} else {
		memobj[id] = 1;
	}
	var turbo = (e.ctrlKey) ? '&turbo=yes' : '';
	DoHiddenDialog("Admin/componentsMove.aspx?page_id=" + page_id + "&component_id=" + id + "&action="+ dirn + turbo);
}
var pageMakeupMoveDownCounts = [];
var pageMakeupMoveUpCounts = [];
function DoHiddenDialog(url) {
	// now use AJAX
	var ajax = createAjax();
	if (ajax != null) {
		ajax.open('GET', url + '&u=' + new Date().getTime(), true);
		ajax.onreadystatechange = function() {
		    if (ajax.readyState == 4) {
		        if ((ajax.status >= 200) && (ajax.status < 300)) {
		            if (ajax.responseXML.getElementsByTagName('script').length > 0) {
		                eval(ajax.responseXML.getElementsByTagName('script')[0].firstChild.nodeValue);
		            }
		        }
		        else
		            alert('Unknown error: check your internet connnection and try reloading the page.');
		    } else return false;
		}
		ajax.send(null);
	} else {
		alert('Please use a browser that supports AJAX: try the latest Firefox / Internet Explorer / Safari');
	}
}
function ControlPanel(site_id, section_id, page_id) {
	ShowDialog("Admin/controlpanel.aspx?site_id=" + site_id + "&section_id=" + section_id + "&page_id=" + page_id);
}
function ResourceManager(id, isFolder) {
	var url = (isFolder) ? "Admin/editor/resourcesManager.aspx?resourceFolder_id=" + id : "Admin/editor/resourcesManager.aspx?section_id=" + id;
	if (ffBaseURL) url = ffBaseURL + url;
	var width = 750;
	var height = 450;
	var windowname = "ffRM";
	windowname += Math.round(Math.random() * 10000) + 1;
	var top = Math.round((screen.availHeight/2) - (height/2));
	var left = Math.round((screen.availWidth/2) - (width/2));
	var newWindow = window.open(url, windowname, "status=no,directories=no,toolbar=no,resizable=yes,location=no,menu=no,width=" + width + ",height=" + height + ",screenX=" + left + ",screenY=" + top + ",top=" + top + ",left=" + left);
	newWindow.focus();
}
function SiteManager(id, current_id) {
	ShowDialog("Admin/sitemanager.aspx?id=" + id + "&current_id=" + current_id);
}
function ChangePassword() {
	ShowDialog("Admin/changePassword.aspx");
}
function ResetToken() {
    ShowDialog("Admin/resetToken.aspx");
}
function ShowStatus(text) {
	window.status = text;
	return true;
}

function ModifyPage(id) {
	ShowDialog("Admin/pagesModify.aspx?id=" + id);
}

function ModifyPageDashboard(id) {
    ShowDialog("Admin/pagesModifyDashboard.aspx?id=" + id);
}

function InsertPage(section_id, newssource_id, parent_id) {
    // newssource_id of -1 means blog post (child of page type "blog")
	if (newssource_id != null)
		ShowDialog("Admin/pagesModify.aspx?section_id=" + section_id + "&newssource_id=" + newssource_id + "&parent_id=" + parent_id);
    else if (parent_id != null)
        ShowDialog("Admin/pagesModify.aspx?section_id=" + section_id + "&parent_id=" + parent_id);
	else
		ShowDialog("Admin/pagesModify.aspx?section_id=" + section_id);
}

function ImportExport(page_id) {
	ShowDialog("Admin/importExport.aspx?page_id=" + page_id);
}

function SectionManager(section_id) {
	ShowDialog("Admin/sectionmanager.aspx?id=" + section_id);
}

function ChooseHtml(page_id) {
	var url = "Admin/chooseHtml.aspx?page_id=" + page_id;
	if (ffBaseURL) url = ffBaseURL + url;
	var width = 700;
	var height = 500;
	var windowname = "ffModify";
	windowname += Math.round(Math.random() * 10000) + 1;
	var top = Math.round((screen.availHeight/2) - (height/2));
	var left = Math.round((screen.availWidth/2) - (width/2));
	var newWindow = window.open(url, windowname, "status=no,directories=no,toolbar=no,resizable=yes,location=no,menu=no,width=" + width + ",height=" + height + ",screenX=" + left + ",screenY=" + top + ",top=" + top + ",left=" + left);
	newWindow.focus();
}


function DeletePage(id) {
	ShowDialog("Admin/pagesDelete.aspx?id=" + id, "auto");
}

function UndeletePage(id) {
	ShowDialog("Admin/pagesUndelete.aspx?id= " + id, "auto");
}

function commentsDelete(page, comment) {
	if (window.confirm("Are you sure you want to delete the selected comment?"))
		DoHiddenDialog("Admin/commentsDelete.aspx?page_id=" + page + "&comment_id="+ comment);
}

function commentsApprove(page, comment) {
	DoHiddenDialog("Admin/commentsApprove.aspx?page_id=" + page + "&comment_id="+ comment);
}

function commentsModify(page, comment) {
	ShowDialog("Admin/commentsModify.aspx?page_id=" + page + "&comment_id=" + comment);
}

function ConfirmURL(url, text) {
	if (window.confirm(text))
		DoHiddenDialog(url);
}


function ConfirmRedirectURL(url, text) {
    if (window.confirm(text))
        window.location = url;
}

function getCookie(strName) {
	var cookies, bits;
	cookies = document.cookie.split(";");
	for (i = 0; i < cookies.length; i++) {
		cookies[i] = cookies[i].replace(" ", "");
		bits = cookies[i].split("=");
		if (bits[0] == strName) { return bits[1]; }
	}
	return false;
}

function setTempCookie(strName, strValue) {
	document.cookie = strName + "=" + escape(strValue) + "; path=/;";
}

function ffRedirect(url, referrer) {
    if ((url.substr(0, 1) != 'index.html') && (url.substr(0, 7) != 'http://') && (url.substr(0, 8) != 'https:///')) {
		if (ffBaseURL) url = ffBaseURL + url;
	}
	location.href = url;
}

function CopyPage(id) { ffRedirect("session.aspx?copypage_id=" + id + "&referrer=" + escape(location.href)); }
function PastePage(id) {
    if (($('.component, .floatedcomponent').length == 0) || window.confirm("Would you like to overwrite the contents of the current page with the copied page?\n\nYou can roll back using the View previous versions tool.")) {
        $.ajax({
            url: "Admin/editor/serverside/pastepage.aspx",
            dataType: 'script',
            type: "POST",
            data: "id=" + id,
            error: function() { alert('Error pasting page.  Please check your internet connection. '); }
        });
    }
}

function xBrowserGetElement(elename) {
    return document.getElementById(elename);
}

function ffLinkHelper() {
	var contentDiv = xBrowserGetElement("content");
	var leftBar = xBrowserGetElement("ffLB");
	var networkOnlyLinks = 0;

	window.defaultStatus = "Building page links...";

	networkOnlyLinks += ffLinkHelperDoObj(contentDiv);
	networkOnlyLinks += ffLinkHelperDoObj(leftBar);

	if (networkOnlyLinks > 0) {
		contentDiv.innerHTML = "<div style='border: 2px solid red; padding: 3px; margin-top: 3px'><b>This page contains links that will only function correctly when using the intranet from within the school network.  Such links are marked with this icon: <img src='Templates/linkfile.gif'>.</div>" + contentDiv.innerHTML;
	}

	window.defaultStatus = "";
	ffImageHelper(contentDiv);
}
function ffImageHelper(container) {
	var images = container.getElementsByTagName("IMG");
	for (i = 0; i < images.length; i++) {
		if (images[i].style.height && (images[i].src.indexOf("image.aspx") != -1)) {
			images[i].src += "&height=" + parseInt(images[i].style.height) + "&width=" + parseInt(images[i].style.width);
		}
	}
}
function ffLinkHelperDoObj(node) {

	contentLinks = node.getElementsByTagName("A");
	var thisServer = location.protocol + "//" + location.host + location.port + location.pathname;
	var networkOnlyLinks = 0;

	for (i = 0; i < contentLinks.length; i++) {

			if (contentLinks[i].href && contentLinks[i].innerText != "") {
				tsrc = ""; talt = ""; ttarget="";
				if (contentLinks[i].href.length > 7) {
					if (contentLinks[i].href.substring(0,7) == "mailto:") { tsrc = 'Templates/linkmail.gif'; talt='Link to e-mail address'; }
					if (contentLinks[i].href.substring(0,7) == "index.html\/\/") { 
						// check no same server link
						if (contentLinks[i].href.length >= thisServer.length) {
							if (contentLinks[i].href.substring(0, thisServer.length) != thisServer) {
								tsrc='Templates/linkext.gif'; talt='Link to external web site (opens in a new window)'; ttarget = "_new";
							}
						} else {
							tsrc= 'Templates/linkext.gif'; talt='Link to external web site (opens in a new window)'; ttarget = "_new";
						}
					}
					if (contentLinks[i].href.substring(0,7) == "file:\/\/") {  networkOnlyLinks++; tsrc='Templates/linkfile.gif'; talt='Link to file on network share (only available on internal network)';  }

				}
				if (tsrc != "") {
					// we have a glyph to add
				if (!document.all) {
					var newglyph = document.createElement("img");
					var src = document.createAttribute("src"); src.value = tsrc; newglyph.setAttributeNode(src);
					var border = document.createAttribute("border"); border.value = "0"; newglyph.setAttributeNode(border);
					var alt = document.createAttribute("alt"); alt.value = talt; newglyph.setAttributeNode(alt);
					contentLinks[i].appendChild(newglyph);
					newglyph.style.marginLeft = "3px";
				}
				else {
					contentLinks[i].innerHTML += "<img src='" + tsrc + "' alt='" + talt + "' border=0 style='margin-left: 3px'>";
				}
					if (ttarget != "") { contentLinks[i].target = ttarget; }
				}
			}

	}
	return networkOnlyLinks;
}


function getTop(obj, abs) {

    /*//
    // IE BUG workaround
    if (abs && (obj.style.overflow != ""))
        return 0;

    var top = $(obj).position().top;

    if (getStyle(obj, 'position').toLowerCase() == 'fixed')
        left += ffGetScrollLeft();

    if ((obj.tagName.toLowerCase() != "html") && (obj.tagName.toLowerCase() != "body") && ($(obj).offsetParent().length > 0)) {
        top -= obj.scrollLeft;
        var tag = $(obj).offsetParent()[0].tagName.toLowerCase();
        if ((tag != "html") && (tag != "body"))
            top += getTop($(obj).offsetParent()[0], abs);
    }*/


    return $(obj).offset().top;
}

function getLeft(obj, abs) {

	/*//
	// IE BUG workaround
	if (abs && (obj.style.overflow != ""))
		return 0;

    var left = $(obj).position().left;
	
	if (getStyle(obj, 'position').toLowerCase() == 'fixed')
		left += ffGetScrollLeft();

    if ((obj.tagName.toLowerCase() != "html") && (obj.tagName.toLowerCase() != "body") && ($(obj).offsetParent().length > 0)) {
        left -= obj.scrollLeft;
        var tag = $(obj).offsetParent()[0].tagName;
	    if ((tag != "html") && (tag != "body"))
		    left += getLeft($(obj).offsetParent()[0], abs);
	}*/
    
    return $(obj).offset().left;
}

function getScrollTop(obj) {

	var top = 0
	if (obj.tagName)
		top = obj.scrollTop;
	
	if (obj.parentElement)
		top += getScrollTop(obj.parentElement);

	else if (obj.parentNode)
		top += getScrollTop(obj.parentNode);

    return top;
}

function getScrollLeft(obj) {

	var left = 0
	if (obj.tagName)
		left = obj.scrollLeft;

	if (obj.parentElement)
		left += getScrollLeft(obj.parentElement);

	else if (obj.parentNode)
		left += getScrollLeft(obj.parentNode);

    return left;
}

function jsError() {

	return true;

}

function ffLog(logtext) {
/*   if (document.getElementById('fflogger')) {
        
    } else {
    var div = document.createElement('div');
    div.style.position = 'absolute';
    div.style.top = '0px';
    div.style.left = '0px';
    div.style.backgroundColor = 'white';
        div.id = 'fflogger';
        document.body.appendChild(div);
    }
    document.getElementById('fflogger').innerHTML = document.getElementById('fflogger').innerHTML + "<br>" + logtext;*/
}

function DashboardFollowPage(page_id) {

    var li = $('#dashboard-follow-page');
    var follow = $(li).is('.ff-button-follow-page');

    $.ajax({
        url: "dashboard-subscribe.aspx?page_id=" + page_id + "&on=" + (follow ? "yes" : "no") + "&subscriptionType=followPage",
        dataType: 'xml',
        type: "POST",
        data: {},
        success: function(data, text) {
            $(li).removeClass();
            if (follow) {
                $('span', li).html('Un' + $('span', li).html());
                $(li).addClass('ff-button-unfollow-page');
            }
            else {
                $('span', li).html($('span', li).html().substring(2));
                $(li).addClass('ff-button-follow-page');
            }
        },
        error: function() { alert('Error saving page following.  Check your internet connection and try reloading the page.'); }
    });
}

function DashboardFollowComments(page_id) {

    var li = $('#dashboard-follow-comments');
    var follow = $(li).is('.ff-button-follow-comments');

    $.ajax({
        url: "dashboard-subscribe.aspx?page_id=" + page_id + "&on=" + (follow ? "yes" : "no") + "&subscriptionType=followComments",
        dataType: 'xml',
        type: "POST",
        data: {},
        success: function(data, text) {
            $(li).removeClass();
            if (follow) {
                $('span', li).html('Un' + $('span', li).html());
                $(li).addClass('ff-button-unfollow-comments');
            }
            else {
                $('span', li).html($('span', li).html().substring(2));
                $(li).addClass('ff-button-follow-comments');
            }
        },
        error: function() { alert('Error saving comment following.  Check your internet connection and try reloading the page.'); }
    });
}

function DashboardBookmarkPage(page_id) {

    var li = $('#dashboard-bookmark');
    var on = $(li).is('.ff-button-bookmark-page');

    $.ajax({
        url: "dashboard-subscribe.aspx?page_id=" + page_id + "&on=" + (on ? "yes" : "no") + "&subscriptionType=bookmark",
        dataType: 'xml',
        type: "POST",
        data: {},
        success: function(data, text) {
            $(li).removeClass();
            if (on) {
                $('span', li).html('Un' + $('span', li).html());
                $(li).addClass('ff-button-unbookmark-page');
            }
            else {
                $('span', li).html($('span', li).html().substring(2));
                $(li).addClass('ff-button-bookmark-page');
            }
        },
        error: function() { alert('Error saving bookmark.  Check your internet connection and try reloading the page.'); }
    });
}

function DashboardUnsubscribe(subscription_id, successfn) {
    $.ajax({
        url: "dashboard-subscribe.aspx?&on=no&subscription_id="+subscription_id,
        dataType: 'xml',
        type: "POST",
        data: {},
        success: successfn,
        error: function() { alert('Error saving subscription.  Check your internet connection and try reloading the page.'); }
    });
}

window.onerror = jsError;
addLoadEvent(function() { checkStyles(ffBaseURL + 'Templates/common.css'); });

// collapsible component type
$(function() {
    ffEventHandler.registerEvent("dominsert", function() {
        $('div.collapsible').each(function() {
            // prevent wiring up twice
            if ($(this).is('.collapsible-wired'))
                return;

            var collapsed = true;
            var height = $('h2.componentheader', this).outerHeight(true);
            $(this).css({ 'height': height + 'px', 'overflow': 'hidden' });

            this.ffComponentChangeType = function(obj) {
                $(obj).removeClass('collapsible-wired');
                $(obj).removeClass('collapsible-open');
                $(obj).removeClass('collapsible-shut');
                obj.ffComponentChangeType = null;
                $(obj).css({ 'height': '', 'overflow': '' });
            }

            $('h2.componentheader', this).click(function() {
                if (collapsed) {
                    $(this.parentNode).css({ 'height': 'auto', 'overflow': 'auto' });
                    $(this.parentNode).addClass('collapsible-open');
                    $(this.parentNode).removeClass('collapsible-shut');
                } else {
                    $(this.parentNode).css({ 'height': height + 'px', 'overflow': 'hidden' });
                    $(this.parentNode).removeClass('collapsible-open');
                    $(this.parentNode).addClass('collapsible-shut');
                }
                collapsed = !collapsed;
            });

            $(this).addClass('collapsible-wired');
            $(this).addClass('collapsible-shut');
        });
    }, true);
});
function ffQMC() {
    if (document.compatMode == 'BackCompat') {
        document.write("<div class='backcompat warningbox infobox' style='margin-top: 1em'>Your site's Firefly template is out of date.  Some Firefly features may work more slowly, or not at all, in some browsers.  Please contact <a href='http://fireflysolutions.co.uk/'>Firefly support</a> for more information, quoting <em>Quirks Mode Template</em>.  This message is only shown to site administrators.</div>");
    }
}
function ffLoadScript(src, destination, onload) {
    // check for duplication
    var scripts = document.getElementsByTagName('script');
    var seen = false;
    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].getAttribute('src')) {
            if (scripts[i].getAttribute('src') == src) {
                seen = true;
                break;
            }
        }
    }
    // add to DOM
    if (!seen) {
        var head = document.getElementsByTagName('head')[0];
        var node = document.createElement('script');
        node.setAttribute('type', 'text/javascript');
        node.setAttribute('src', src);

        if (onload) {
            if (node.readyState) {
                node.onreadystatechange = function() {
                    if (node.readyState == "loaded" ||
      	                node.readyState == "complete") {
                        node.onreadystatechange = null;
                        onload();
                    }
                };
            } else {
                node.onload = function() {
                    onload();
                };
            }
        }

        if (destination != 'here') {
            head.appendChild(node);
        }
        else {
            document.write(node.outerHTML);
        }
    } else {
        if (onload) onload();
    }
}
function isMobile() {
    return ($(window).width() < ffMobileWidth);
}

function ffConfirm(msg, url) {
    if (confirm(msg))
        window.location = url;
}
